// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

mod tray;

use tauri::{generate_context, generate_handler, Manager, Runtime, WebviewWindow};

#[tauri::command]
async fn fullscreen_window<R: Runtime>(window: WebviewWindow<R>) {
    if let Some(main_window) = window.get_webview_window("main_admin") {
        // 直接最大化而不关闭窗口
        main_window.set_fullscreen(true).unwrap(); // 使用原生全屏API
    }
}

#[tauri::command]
async fn hide_window<R: Runtime>(window: WebviewWindow<R>) {
    if let Some(main_window) = window.get_webview_window("main_admin") {
        // 直接最大化而不关闭窗口
        main_window.hide().unwrap(); // 使用原生全屏API
    }
}

#[tauri::command]
async fn login_success<R: Runtime>(window: WebviewWindow<R>) -> Result<(), String> {
    if let Some(main_window) = window.get_webview_window("main_window") {
        // 设置为全屏
        main_window.set_fullscreen(true).map_err(|e| e.to_string())?;

        // 跳转到主界面
        main_window.eval("window.location.href = '/';")
            .map_err(|e| e.to_string())?;

        Ok(())
    } else {
        Err("Main window not found".to_string())
    }
}

#[tauri::command]
async fn close_splashscreen<R: Runtime>(window: WebviewWindow<R>) -> Result<(), String> {
    println!("开始关闭窗口");
    if let Some(splashscreen) = window.get_webview_window("splashscreen") {
        splashscreen.close().unwrap();
    }
    let main_window = if let Some(window) = window.get_webview_window("main_window") {
        window
    } else {
        return Err("Main window not found".to_string());
    };
    // 显示主窗口
    main_window.show().map_err(|e| e.to_string())?;

    Ok(())
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            let app_handle = app.handle();
            // 初始化托盘
            tray::create_tray(&app_handle).expect("Failed to create tray");
            Ok(())
        })
        .invoke_handler(generate_handler![
            close_splashscreen,
            hide_window,
            login_success,
            fullscreen_window
        ])
        .run(generate_context!())
        .expect("error while running tauri application");
}